/******************************************************************
系统名称:E比价
类  名  称: UnlockPatternActivity.java
软件版权: 恒生电子股份有限公司
系统版本: 1.0
开发人员: maqf
开发时间: 2015-04-01
功能说明: 手势密码锁
审核人员: 
相关文档: 
修改记录: 需求编号         修改日期         修改人员                     修改说明
 
******************************************************************/
package com.hundsun.fcp.activity;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hundsun.fcp.FcpApplication;
import com.hundsun.fcp.R;
import com.hundsun.fcp.base.BaseActivity;
import com.hundsun.fcp.common.Redirect;
import com.hundsun.fcp.common.AppointFiled.IntentKeyDef;
import com.hundsun.fcp.common.AppointFiled.IntentValueDef;
import com.hundsun.fcp.common.AppointFiled.RequestCodeDef;
import com.hundsun.fcp.common.utils.CommonDialog;
import com.hundsun.fcp.manager.FcpUserManager;
import com.hundsun.fcp.manager.SettingManager;
import com.hundsun.fcp.manager.SettingManager.FcpUserSetting;
import com.hundsun.fcp.widget.lockpattern.LockPatternUtils;
import com.hundsun.fcp.widget.lockpattern.LockPatternView;
import com.hundsun.fcp.widget.lockpattern.LockPatternView.Cell;


public class UnlockPatternActivity extends BaseActivity  implements  LockPatternView.OnPatternListener{
	
	protected int FAILED_COUNT = 0;
	protected int FAILED_MAX = 5;
	protected int VERIFY_PASSWORD_COUNT = 0;
	protected int VERIFY_PASSWORD_MAX = 3;
	private final AtomicBoolean isExit = new AtomicBoolean(false);
	protected LockPatternView lockpattern;
	private ImageView mUserHeadView ;
	protected TextView mHeaderText;
	private TextView mForgetPattern ;
	private TextView mLogout ;
	protected LockPatternUtils mLockPatternUtils;
	private AlertDialog dialog;
	
	private int locktype ;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setNeedLock(false) ;
		locktype = getIntent().getIntExtra(IntentKeyDef.LOCK_PWD_TYPE,IntentValueDef.DEFUALT) ;
		if(locktype==IntentValueDef.DEFUALT){
			mHeaderMenu.showHeader(false) ;
		}else{
			mUserHeadView.setVisibility(View.GONE) ;
			mHeaderMenu.showHeader(true) ;
			mHeaderMenu.toggleRight(View.INVISIBLE) ;
			mHeaderMenu.setTitle(R.string.lockpattern_modify_tip) ;
		}
	}
	

	@Override
	public void initView() {
		FAILED_COUNT = FcpUserSetting.getLockErrorCount() ;
		lockpattern = (LockPatternView) findViewById(R.id.lockpattern) ;	
		mUserHeadView = (ImageView) findViewById(R.id.iv_head) ;
		mHeaderText = (TextView) findViewById(R.id.mHeaderText) ;
		mForgetPattern = (TextView) findViewById(R.id.tv_forget_pattern) ;
		mLogout = (TextView) findViewById(R.id.tv_logout) ;
		this.mLockPatternUtils = new LockPatternUtils(this);
		this.lockpattern.setOnPatternListener(this);
		mForgetPattern.setOnClickListener(clickListener) ;
		mLogout.setOnClickListener(clickListener) ;
	}
	
	private OnClickListener clickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(v == mForgetPattern){
				CommonDialog.showAlert(UnlockPatternActivity.this, R.string.app_name, R.string.dialog_forget_lockpattern,
						R.string.dialog_forget_lockpattern_relogin, R.string.dialog_button_cancel, 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								forgetPattern() ;
							}
						}, 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss() ;
							}
						}) ;
				
			}else if(v==mLogout){
				clickLogout() ;
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if (this.FAILED_MAX <= this.FAILED_COUNT) {
			onFailed();
		}
	}
	
	protected void forgetPattern() {
		Redirect.startModifyGesturePwd(this, RequestCodeDef.PARTTERN_REQUEST_CODE_FORGET) ;
	}

	private void exitBy2Click()
	{
		if (!this.isExit.getAndSet(true))
	    {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.out_later), Toast.LENGTH_SHORT).show();    
	      new Handler().postDelayed(new Runnable()
	      {
	        public void run()
	        {
	          UnlockPatternActivity.this.isExit.set(false);
	        }
	      }, 2000L);
	      return;
	    }
	    quitApplication();
	}
	
	@Override
	public void onPatternStart() {}

	@Override
	public void onPatternCleared() {}

	@Override
	public void onPatternCellAdded(List<Cell> pattern) {}

	@Override
	public void onPatternDetected(List<Cell> pattern) {
		if (pattern == null)
			return;
		if (mLockPatternUtils.checkPattern(pattern)) {
			unlockPattern();
			setResult(RESULT_OK);
			finish();
		}else{
			FAILED_COUNT = 1 + FAILED_COUNT;
			FcpUserSetting.setLockErrorCount(FAILED_COUNT) ;
			if (FAILED_COUNT >= FAILED_MAX)
			{
				mHeaderText.setTextColor(0xffff0000);
				mHeaderText.setText( R.string.lockpattern_fail_too_more);
				lockpattern.clearPattern();
				onFailed();
				return;
			} else
			{
				int i = 5 - FAILED_COUNT;
				mHeaderText.setTextColor(0xffff0000);
				mHeaderText.setText((new StringBuilder()).append("密码错误，还可以再输入").append(i).append("次").toString());
				mHeaderText.startAnimation(AnimationUtils.loadAnimation(this,R.anim.shake));
				lockpattern.clearPattern();
				return;
			}
		}
		
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState); 
		FAILED_COUNT = FcpUserSetting.getLockErrorCount() ;
	}
	
	 @Override
	protected void onSaveInstanceState(Bundle outState) {
		 super.onSaveInstanceState(outState); 
		 FcpUserSetting.setLockErrorCount(FAILED_COUNT) ;
	}
	 
	private void onFailed() {
		
		 CommonDialog.showAlert(this, R.string.app_name, R.string.lockpattern_fail_too_more_click_ok, 
					new DialogInterface.OnClickListener() {
					public void onClick(
						DialogInterface paramAnonymousDialogInterface,
						int paramAnonymousInt) {
					SettingManager.FcpUserSetting.setLockPattern(false) ;
					UnlockPatternActivity.this.logout();
				}
			},new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SettingManager.FcpUserSetting.setLockPattern(false) ;
					cleanStored(); 
					finish() ;
				}
			}) ;
		
	}
	
	protected void verifyPassword()
	{
		if (this.VERIFY_PASSWORD_COUNT >= this.VERIFY_PASSWORD_MAX)
		{
	      CommonDialog.showAlert(this, R.string.app_name, R.string.verifypwd_too_more, 
					new DialogInterface.OnClickListener() {
					public void onClick(
						DialogInterface paramAnonymousDialogInterface,
						int paramAnonymousInt) {
					UnlockPatternActivity.this.logout();
				}
			},null) ;
	      
	      return;
	    }
	     
	  }

	protected void logout() { 
		cleanStored();
	    Intent _Intent = new Intent(this, MainActivity.class);
	    startActivity(_Intent);
	    finish();
	}

	private void cleanStored() {
		FcpUserManager.getInstance().cleanStoredUserInfo() ;
		//FcpApplication.getInstance().getLoginObservable().notifyObservers("0") ;
	}
	
	public void clickLogout() {
		CommonDialog.showAlert(this, R.string.app_name, R.string.logout_confirm, 
				new DialogInterface.OnClickListener() {
				public void onClick(
					DialogInterface paramAnonymousDialogInterface,
					int paramAnonymousInt) {
				UnlockPatternActivity.this.logout();
			}
		},null) ;
	}
	
	 @Override
	public void onBackPressed() {
		 if(locktype==IntentValueDef.DEFUALT)
			 exitBy2Click() ;
		 else 
			 super.onBackPressed() ;
	}
	 
	 private void createLockPattern() {
		 startActivityForResult(new Intent(this,LockPatternCreateActivity.class), RequestCodeDef.PARTTERN_REQUEST_CODE_CREATE);
	}
	 
	 @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode==RESULT_OK){
			if(requestCode == RequestCodeDef.PARTTERN_REQUEST_CODE_FORGET){
				createLockPattern() ;
				return ;
			}
		}
		
		if(requestCode == RequestCodeDef.PARTTERN_REQUEST_CODE_CREATE){
			if(resultCode==RESULT_OK){
				setResult(RESULT_OK) ;
				finish() ;
				return ;
			}else{
				CommonDialog.showAlert(this, R.string.app_name, R.string.close_lockpattern_confirm,
						R.string.sure_close, R.string.continue_setting,
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								mLockPatternUtils.clearLock() ;
								UnlockPatternActivity.this.finish() ;
							}
						}, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								UnlockPatternActivity.this.createLockPattern();
							}
						}) ;
			}
		}
	}

	@Override
	protected int getContentLayout() {
		return R.layout.activity_unlock_pattern;
	}
}
